#include "EventRaw.h"

#include "EventObject.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct _EventRaw
{
	EventObject parent_instace;
	epointer    data;
	euint32	    size;
};

static void
event_raw_finalize(EventRaw *self)
{
	if (self->data)
		free(self->data);
}

EventRaw *
event_raw_new(euint32 size)
{
	EventRaw *object;

	object = MALLOC_NEW(EventRaw);
	event_object_init(EVENT_OBJECT(object));
	event_object_set_finalize(object, FINALIZE(event_raw_finalize));

	object->size = size;
	if (size == 0) {
		object->data = NULL;
	} else {
		object->data = malloc(size);
		memset(object->data, 0, size);
	}

	return object;
}

EventRaw *
event_raw_new_with_stream(euint32 size, epointer raw)
{
	EventRaw *object = event_raw_new(size);

	return_val_if_fail(object != NULL, event_raw_new_with_stream, NULL);

	memcpy(object->data, raw, size);
	return object;
}

euint32
event_raw_get_size(EventRaw *self)
{
	return_val_if_fail(self != NULL, event_raw_get_size, 0);
	return self->size;
}

epointer
event_raw_get_data(EventRaw *self)
{
	return_val_if_fail(self != NULL, event_raw_get_data, NULL);
	return self->data;
}

void
event_raw_add_data(EventRaw *self, euint32 size, epointer raw_steam)
{
	epointer cache;
	return_if_fail(self != NULL, event_raw_add_data);

	if (size == 0)
		return;

	cache = malloc(self->size + size);
	if (self->size > 0)
		memcpy(cache, self->data, self->size);
	memcpy(cache + self->size, raw_steam, size);
	if (self->data)
		free(self->data);
	self->size += size;
	self->data  = cache;
}
